﻿using HartConfigTool.SerialPortUtil;
using HartConfigTool.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HartConfigTool.HARTCommands
{
    public abstract class CMDsBase : ICommand
    {
        protected SerialPortsManager serialPortManager;
        public bool IsCompleted { get; set; }

        public void ConfigurationParameters(SerialPortsManager serialPortManager)
        {
            this.serialPortManager = serialPortManager;
            this.serialPortManager.SetCurrentCMD(this);
        }
        public async Task ExecuteCMD()
        {
            await SendCMDAsync();
        }
        protected abstract Task SendCMDAsync();
        public abstract Task ParseResponse(byte[] responseData);
        public static byte[] StructToBytes<T>(T structVar)
        {
            int size = Marshal.SizeOf(structVar);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.StructureToPtr(structVar, ptr, true);
                Marshal.Copy(ptr, arr, 0, size);
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }

            return arr;
        }
        public void RegisterObserver(ref Dictionary<string, IObserver> CMDObservers, string observerName, IObserver observerObj)
        {
            if (CMDObservers.ContainsKey(observerName))
            {
                UnregisterObserver(ref CMDObservers, observerName);
            }
            CMDObservers.Add(observerName, observerObj);
        }
        public void UnregisterObserver(ref Dictionary<string, IObserver> CMDObservers, string observerName)
        {
            CMDObservers.Remove(observerName);
        }
        public void NotifyObservers(Dictionary<string, IObserver> observers, string dataSegmentName, List<string> listStr)
        {
            if (observers.ContainsKey(dataSegmentName))
            {
                observers[dataSegmentName].Update(listStr);
            }
        }
    }
}
